//
//  MailBoxViewController.m
//  Utils
//
//  Created by enghou on 2018/4/12.
//  Copyright © 2018年 xyxorigation. All rights reserved.
//

#import "MailBoxViewController.h"
#import "NetWorkerManager.h"
#import "MailDetailViewController.h"
#import "MailBoxItemModel.h"
#import "SearchMailViewController.h"
@interface MailBoxViewController ()

@end

@implementation MailBoxViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"收件箱";
    [self configUI];
    [self beginRefresh];
}

-(void)configUI{
    UIBarButtonItem *search = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemSearch target:self action:@selector(searchAction)];
    search.tintColor = [UIColor whiteColor];
    UIBarButtonItem *edit = [[UIBarButtonItem alloc]initWithTitle:@"编辑" style:UIBarButtonItemStylePlain target:self action:@selector(editAction:)];
    edit.tintColor = [UIColor whiteColor];
    self.navigationItem.rightBarButtonItems = @[edit,search];
    [self.tableView registerNib:[UINib nibWithNibName:@"MailTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"MailTableViewCell"];
    self.tableView.allowsMultipleSelectionDuringEditing = YES;
    self.tableView.backgroundColor = [UIColor defaultBackgroundColor];
}

-(void)beginRefresh{
    [self beginLoading];
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    if ([self.mail_title length] > 0) {
        [param setObject:self.mail_title forKey:@"searchPlatformMessageVo.title"];
    }
    if ([self.sender length]> 0) {
        [param setObject:self.sender forKey:@"searchPlatformMessageVo.senderName"];
    }
    if ([self.msg_type length] > 0) {
        [param setObject:self.msg_type forKey:@"searchPlatformMessageVo.messageType"];
    }
    if ([self.beginTime length] > 0) {
        [param setObject:self.beginTime forKey:@"searchPlatformMessageVo.sendTimeStart"];
    }
    if ([self.endTime length] > 0) {
        [param setObject:self.endTime forKey:@"searchPlatformMessageVo.sendTimeEnd"];
    }
    [[NetWorkerManager sharedInstance]getMailListWithPage:1 condition:param successBlock:^(BaseModel *model) {
        [self endLoading];
        if (model.success) {
            [self refreshSuccessWithModel:model];
        }else{
            [self commonFailBlockWithModel:model];
        }
    } failBlock:^(NSInteger code) {
        [self endLoading];
        [self alertSome:kNetWorkFail];
    }];
}

-(void)loadNext{
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    if ([self.mail_title length] > 0) {
        [param setObject:self.mail_title forKey:@"searchPlatformMessageVo.title"];
    }
    if ([self.sender length]> 0) {
        [param setObject:self.sender forKey:@"searchPlatformMessageVo.senderName"];
    }
    if ([self.msg_type length] > 0) {
        [param setObject:self.msg_type forKey:@"searchPlatformMessageVo.messageType"];
    }
    if ([self.beginTime length] > 0) {
        [param setObject:self.beginTime forKey:@"searchPlatformMessageVo.sendTimeStart"];
    }
    if ([self.endTime length] > 0) {
        [param setObject:self.endTime forKey:@"searchPlatformMessageVo.sendTimeEnd"];
    }
    [self beginLoading];
    [[NetWorkerManager sharedInstance]getMailListWithPage:self.page+1 condition:param successBlock:^(BaseModel *model) {
        [self endLoading];
        if (model.success) {
            [self loadMoreSuccessWithModel:model];
        }else{
            [self commonFailBlockWithModel:model];
        }
    } failBlock:^(NSInteger code) {
        [self endLoading];
        [self alertSome:kNetWorkFail];
    }];
}

-(void)markRead:(NSString *)item_id{
    [[NetWorkerManager sharedInstance]markReadWithId:item_id successBlock:^(BaseModel *model) {
        
    } failBlock:^(NSInteger code) {
        
    }];
}

-(void)deleteAnItemWithId:(NSString *)item_id{
    [[NetWorkerManager sharedInstance]delMailWithId:item_id successBlock:^(BaseModel *model) {
        if (model.success) {
            
        }else{
            [self commonFailBlockWithModel:model];
        }
    } failBlock:^(NSInteger code) {
        [self alertSome:kNetWorkFail];
    }];
}

- (UIImage  *)xy_noDataViewImage{
    return [UIImage imageNamed:@"icon_no_data"];
}           //  使用默认占位图, 提供一张图片,    可不提供, 默认不显示
- (NSString *)xy_noDataViewMessage{
    return @"暂时没有邮件";
}

-(void)searchAction{
    UIStoryboard *story = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
    SearchMailViewController *search = [story instantiateViewControllerWithIdentifier:@"SearchMailViewController"];
    search.theDelete = self;
    [self push:search];
}

-(void)selectAllOrNot:(UIBarButtonItem *)item{
    if ([item.title isEqualToString:@"全选"]) {
        item.title = @"全不选";
        [self.source enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            NSIndexPath *index = [NSIndexPath indexPathForRow:idx inSection:0];
            [self.tableView selectRowAtIndexPath:index animated:YES scrollPosition:UITableViewScrollPositionNone];
        }];
    }else{
        item.title = @"全选";
        [self.source enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            NSIndexPath *index = [NSIndexPath indexPathForRow:idx inSection:0];
            [self.tableView deselectRowAtIndexPath:index animated:YES];
        }];
    }
}

-(void)editAction:(UIBarButtonItem *)item{
    if ([item.title isEqualToString:@"编辑"]) {
        [item setTitle:@"删除"];
        self.tableView.editing = YES;
        UIBarButtonItem *selectAll = [[UIBarButtonItem alloc]initWithTitle:@"全选" style:UIBarButtonItemStylePlain target:self action:@selector(selectAllOrNot:)];
        selectAll.tintColor = [UIColor whiteColor];
        self.navigationItem.rightBarButtonItems = @[item,selectAll];
    }else if ([item.title isEqualToString:@"删除"]){
        UIBarButtonItem *search = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemSearch target:self action:@selector(searchAction)];
        search.tintColor = [UIColor whiteColor];
        self.navigationItem.rightBarButtonItems = @[item,search];
        [item setTitle:@"编辑"];
        NSMutableArray *delArrays = [NSMutableArray array];
        for (NSIndexPath *path in self.tableView.indexPathsForSelectedRows) {
            NSInteger row = path.row;
            MailBoxItemModel *model = [self.source objectAtIndex:row];
            [delArrays addObject:model];
            [self deleteAnItemWithId:model.ids];
        }
        for (MailBoxItemModel *model in delArrays) {
            [self.source removeObject:model];
            self.totalRecords--;
        }
        if (self.totalRecords==0) {
            self.full = NO;
        }
        [self.tableView beginUpdates];
        [self.tableView deleteRowsAtIndexPaths:self.tableView.indexPathsForSelectedRows withRowAnimation:UITableViewRowAnimationFade];
        [self.tableView endUpdates];
        [self.tableView reloadData];
        self.tableView.editing = NO;
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    return [tableView dequeueReusableCellWithIdentifier:@"MailTableViewCell"];
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (!tableView.editing) {
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
        MailBoxItemModel *model = [self.source objectAtIndex:indexPath.row];
        model.readyet = YES;
        [self.tableView reloadData];
        MailDetailViewController *mail = [[MailDetailViewController alloc]init];
        mail.mailId = model.ids;
        mail.theDelete = self;
        mail.title = @"收件详情";
        [self markRead:model.ids];
        [self push:mail];
    }
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleDelete | UITableViewCellEditingStyleInsert;
}

-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    MailBoxItemModel *model = [self.source objectAtIndex:indexPath.row];
    [self.source removeObject:model];
    [self.tableView beginUpdates];
    [self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    [self.tableView endUpdates];
    [self deleteAnItemWithId:model.ids];
}

-(void)delAItemWithId:(NSString *)item_id{
    [self.source enumerateObjectsUsingBlock:^(MailBoxItemModel *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([obj.ids isEqualToString:item_id]) {
            [self.source removeObject:obj];
            self.totalRecords --;
            if (self.totalRecords == 0) {
                self.full = NO;
            }
            [self.tableView reloadData];
            return ;
        }
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
